package com.utils.network.factory;

import androidx.annotation.AnyRes;
import androidx.lifecycle.LiveData;

import com.utils.network.api.ApiResponse;

import org.jetbrains.annotations.NotNull;

import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.IllformedLocaleException;

import retrofit2.CallAdapter;
import retrofit2.Retrofit;

public class LiveDataCallAdapterFactory extends CallAdapter.Factory {

    @Override
    public CallAdapter<?, ?> get(@NotNull Type returnType, @NotNull Annotation[] annotations, @NotNull Retrofit retrofit) {
        if (getRawType(returnType) != LiveData.class) {
            return null;
        }
        Type observableType = getParameterUpperBound(0, (ParameterizedType) returnType);
        Class rawType = getRawType(observableType);
        if (rawType != ApiResponse.class) {
            throw new IllegalArgumentException("必须是ApiResponse类型");
        }
        if (!(observableType instanceof ParameterizedType)) {
            throw new IllformedLocaleException("resource must be parameterized");
        }
        return new LiveDataCallAdapter<>(observableType);
    }
}
